package com.supermap.desktop.ui.controls;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

import com.supermap.data.Datasource;
import com.supermap.data.Datasources;
import com.supermap.desktop.Application;
import com.supermap.desktop.CommonToolkit;

public class DatasourceComboBox extends JComboBox<Object> {
	private static final long serialVersionUID = 1L;

	/**
	 * 根据工作空间中已经有的数据源集合类创建下拉选择框
	 * 
	 * @param datasets
	 */
	public DatasourceComboBox() {
		super(initDatasourceComboBoxItem());
		ListCellRenderer<Object> renderer = new CommonListCellRenderer();
		setRenderer(renderer);
	}

	/**
	 * 根据给定的数据源集合类创建下拉选择框
	 * 
	 * @param datasets
	 */
	public DatasourceComboBox(Datasources datasources) {
		super(initDatasourceComboBoxItem(datasources));
		ListCellRenderer<Object> renderer = new CommonListCellRenderer();
		setRenderer(renderer);
	}

	/**
	 * 根据给定的数据源集合创建下拉选择框
	 * 
	 * @param datasets
	 */
	public DatasourceComboBox(Datasource[] datasources) {
		super(initDatasourceComboBoxItem(datasources));
		ListCellRenderer<Object> renderer = new CommonListCellRenderer();
		setRenderer(renderer);
	}

	/**
	 * 由于填充的是DatasetCell 返回时需要得到DatasetCell中JLabel中显示的字符串
	 * 
	 * @return
	 */
	public String getSelectItem() {
		DataCell temp = (DataCell) getSelectedItem();
		return temp.getDatasetName();
	}

	private static JPanel[] initDatasourceComboBoxItem(Datasources datasources) {
		JPanel[] result = new JPanel[datasources.getCount()];
		for (int i = 0; i < datasources.getCount(); i++) {
			String filePath = CommonToolkit.DatasourceImageWrap.getImageIconPath(datasources.get(i).getEngineType());
			String datasourceAlis = datasources.get(i).getAlias();
			result[i] = new DataCell(filePath, datasourceAlis);
		}
		return result;
	}

	private static JPanel[] initDatasourceComboBoxItem() {
		Datasources datasources = Application.getActiveApplication().getWorkspace().getDatasources();
		return initDatasourceComboBoxItem(datasources);
	}

	private static JPanel[] initDatasourceComboBoxItem(Datasource[] datasources) {
		JPanel[] result = new JPanel[datasources.length];
		for (int i = 0; i < datasources.length; i++) {
			String filePath = CommonToolkit.DatasourceImageWrap.getImageIconPath(datasources[i].getEngineType());
			String datasourceAlis = datasources[i].getAlias();
			result[i] = new DataCell(filePath, datasourceAlis);
		}
		return result;
	}
}
